// 将设备检测函数移到全局作用域
function isMobileDevice() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) 
        || window.innerWidth <= 768;
}

document.addEventListener('DOMContentLoaded', function() {
    // 导航栏配置
    const navConfig = [
        {
            id: 'threeD',
            name: '3D游戏',
            icon: 'fas fa-cube'
        },
        {
            id: 'casual',
            name: '超休闲',
            icon: 'fas fa-mobile-alt'
        },
        {
            id: 'card',
            name: '卡牌游戏',
            icon: 'fas fa-clone'
        },
        {
            id: 'physics',
            name: '物理游戏',
            icon: 'fas fa-atom'
        }
    ];

    // 游戏数据配置
    const gamesData = {
        threeD: [
            {
                title: "迷失深空",
                image: "3d1.jpg",
                category: "3D游戏",
                description: "探索神秘的太空站，解开消失的宇航员之谜...",
                rating: "9.2",
                year: "2023",
                url: "https://game1.example.com"
            },
            {
                title: "森林冒险",
                image: "3d2.jpg",
                category: "3D游戏",
                description: "在广阔的森林中探索，建造庇护所，对抗野兽...",
                rating: "8.9",
                year: "2023",
                url: "https://game2.example.com"
            }
        ],
        casual: [
            {
                title: "水果消消乐",
                image: "casual1.jpg",
                category: "超休闲",
                description: "轻松有趣的三消游戏，简单上手，富有挑战性...",
                rating: "9.0",
                year: "2024",
                url: "https://game3.example.com"
            },
            {
                title: "跑酷大师",
                image: "casual2.jpg",
                category: "超休闲",
                description: "无尽的跑酷挑战，收集金币，躲避障碍...",
                rating: "8.8",
                year: "2024",
                url: "https://game4.example.com"
            }
        ],
        card: [
            {
                title: "魔法对决",
                image: "card1.jpg",
                category: "卡牌游戏",
                description: "策略性卡牌对战游戏，收集卡牌，组建最强卡组...",
                rating: "9.5",
                year: "2024",
                url: "https://game5.example.com"
            },
            {
                title: "卡牌地下城",
                image: "card2.jpg",
                category: "卡牌游戏",
                description: "融合地下城探索与卡牌战斗的创新玩法...",
                rating: "9.3",
                year: "2023",
                url: "https://game6.example.com"
            }
        ],
        physics: [
            {
                title: "弹跳世界",
                image: "physics1.jpg",
                category: "物理游戏",
                description: "基于真实物理引擎的解谜游戏，充满趣味的物理玩法...",
                rating: "9.1",
                year: "2024",
                url: "https://game7.example.com"
            },
            {
                title: "重力迷宫",
                image: "physics2.jpg",
                category: "物理游戏",
                description: "操控重力方向，引导小球到达终点...",
                rating: "8.9",
                year: "2023",
                url: "https://game8.example.com"
            }
        ]
    };

    // 生成导航栏的函数
    function renderNav() {
        const categoriesContainer = document.querySelector('.game-categories');
        categoriesContainer.innerHTML = navConfig.map(category => `
            <div class="category" data-category="${category.id}">
                <i class="${category.icon}"></i>
                <span>${category.name}</span>
            </div>
        `).join('');
    }

    // 生成导航栏
    renderNav();

    // 获取分类和容器元素（移到renderNav之后）
    const categories = document.querySelectorAll('.category');
    const gamesContainer = document.querySelector('.games-container');

    // 分类名称映射表（从navConfig自动生成）
    const categoryMap = Object.fromEntries(
        navConfig.map(category => [category.name, category.id])
    );

    // 获取分类图标的函数（从navConfig获取）
    function getCategoryIcon(category) {
        const categoryConfig = navConfig.find(config => config.id === category);
        return categoryConfig ? categoryConfig.icon : navConfig[0].icon;
    }

    // 创建游戏卡片的函数
    function createGameCard(game, category) {
        return `
            <div class="game-card" data-category="${category}" data-url="${game.url}">
                <div class="game-content">
                    <div class="game-image">
                        <img src="${game.image}" alt="${game.title}">
                    </div>
                    <div class="game-info">
                        <h3>${game.title}</h3>
                        <p class="game-category">
                            <i class="${getCategoryIcon(category)}"></i> ${game.category}
                        </p>
                        <p class="game-description">${game.description}</p>
                        <div class="game-meta">
                            <span><i class="fas fa-star"></i> ${game.rating}</span>
                            <span><i class="fas fa-calendar"></i> ${game.year}</span>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    // 渲染游戏卡片的函数
    function renderGames(category) {
        gamesContainer.innerHTML = '';
        const games = category ? gamesData[category] : Object.values(gamesData).flat();
        
        games.forEach(game => {
            gamesContainer.innerHTML += createGameCard(game, category || game.category.toLowerCase());
        });
    }

    // 添加分类点击事件
    categories.forEach(category => {
        category.addEventListener('click', function() {
            categories.forEach(c => c.classList.remove('active'));
            this.classList.add('active');

            const categoryName = this.querySelector('span').textContent;
            const selectedCategory = categoryMap[categoryName];
            renderGames(selectedCategory);
        });
    });

    // 初始化显示3D游戏
    const threeDCategory = Array.from(categories).find(category => 
        category.querySelector('span').textContent === navConfig[0].name
    );
    
    if (threeDCategory) {
        threeDCategory.classList.add('active');
        renderGames(navConfig[0].id);
    }

    // 计算并显示游戏总数
    function updateGameCount() {
        const totalGames = Object.values(gamesData).reduce((total, games) => total + games.length, 0);
        document.getElementById('totalGames').textContent = totalGames;
    }

    // 初始化时更新游戏数量
    updateGameCount();

    // 修改游戏卡片点击事件
    gamesContainer.addEventListener('click', function(e) {
        const card = e.target.closest('.game-card');
        if (card) {
            const url = card.dataset.url;
            
            if (isMobileDevice()) {
                // 手机端直接跳转
                window.location.href = url;
            } else {
                // PC端显示模态框
                showGameModal(url);
            }
        }
    });

    // 添加模态框关闭事件（仅在PC端需要）
    if (!isMobileDevice()) {
        document.querySelector('.modal-close').addEventListener('click', hideGameModal);
        document.querySelector('.modal-overlay').addEventListener('click', hideGameModal);
    }

    // 添加显示提示函数
    function showToast() {
        const toast = document.getElementById('copyToast');
        toast.classList.add('show');
        
        setTimeout(() => {
            toast.classList.remove('show');
        }, 2000);
    }

    // 修改复制功能中的成功处理
    document.querySelectorAll('.copy-btn').forEach(button => {
        button.addEventListener('click', async function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const textToCopy = this.dataset.copy;
            
            try {
                await navigator.clipboard.writeText(textToCopy);
                
                // 显示复制成功图标
                const originalIcon = this.innerHTML;
                this.innerHTML = '<i class="fas fa-check"></i>';
                
                // 显示提示
                showToast();
                
                setTimeout(() => {
                    this.innerHTML = originalIcon;
                }, 1000);
                
            } catch (err) {
                const tempInput = document.createElement('input');
                tempInput.style.position = 'absolute';
                tempInput.style.left = '-9999px';
                tempInput.value = textToCopy;
                document.body.appendChild(tempInput);
                
                tempInput.select();
                try {
                    document.execCommand('copy');
                    
                    // 显示复制成功图标
                    const originalIcon = this.innerHTML;
                    this.innerHTML = '<i class="fas fa-check"></i>';
                    
                    // 显示提示
                    showToast();
                    
                    setTimeout(() => {
                        this.innerHTML = originalIcon;
                    }, 1000);
                } catch (err) {
                    console.error('复制失败:', err);
                }
                
                document.body.removeChild(tempInput);
            }
        });
    });
});

// 修改showGameModal函数
function showGameModal(url) {
    // 如果是移动设备，直接返回
    if (isMobileDevice()) {
        return;
    }

    const modal = document.querySelector('.game-modal');
    const gameFrame = document.getElementById('gameFrame');
    const qrContainer = document.getElementById('qrContainer');
    
    // 清除现有二维码
    qrContainer.innerHTML = '';
    
    // 生成新的二维码
    new QRCode(qrContainer, {
        text: url,
        width: 280,  // 增加二维码尺寸
        height: 280,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    });
    
    // 设置游戏iframe的src
    gameFrame.src = url;
    
    // 显示模态框
    modal.style.display = 'block';
    document.body.style.overflow = 'hidden';
}

function hideGameModal() {
    const modal = document.querySelector('.game-modal');
    const gameFrame = document.getElementById('gameFrame');
    
    gameFrame.src = '';
    modal.style.display = 'none';
    document.body.style.overflow = '';
} 